package main

import (
	"context"
	"fmt"
	"gbox-one-machine/conf"
	"gbox-one-machine/log"
	"gbox-one-machine/server"
	"github.com/kardianos/service"
	"os"
)

var logger service.Logger

type program struct{}

func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	return nil
}
func (p *program) run() {
	// Do work here
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	conf.Init(ctx)
	cf := conf.GetConf()

	log.InitLogger(cf)

	log.Logger.Info("Config loaded")
	log.Logger.Debugf("Config:\n%s", cf)
	if err := server.Serve(ctx, cf); err != nil {
		log.Logger.Errorf("Server start err:\n%s", err)
	}
	for {
		select {}
	}
}
func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

func main() {
	svcConfig := &service.Config{
		Name:        "gbox_one_machine",
		DisplayName: "gbox_one_machine",
		Description: "This is an example Go service.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Logger.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		log.Logger.Fatal(err)
	}
	if len(os.Args) > 1 {
		if os.Args[1] == "install" {
			err := s.Install()
			fmt.Println(err)
			return
		}
		if os.Args[1] == "remove" {
			err := s.Uninstall()
			fmt.Println(err)
			return
		}
	}
	fmt.Println(333)
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
